package demo.core;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.model.Styles;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.model.ThemesTable;
import org.apache.poi.xssf.usermodel.*;

import java.awt.*;
import java.io.*;
import java.util.logging.Logger;

/**
 * @author 63495
 * @Description: XML文件操作demo//
 * @date 2022/3/21 22:40
 */
public class XMLDemo {

    public static void main(String[] args) throws IOException, InvalidFormatException {
        // 创建一个文件对象

        // 从这里读取
        final var resourcePath = "C:\\Users\\63495\\Desktop\\dzp.csv";
        // 往这里写入
        final var targetPath = "C:\\Users\\63495\\Desktop\\dzp.xlsx";
        File resourceFile = new File(resourcePath);
        File targetFile = new File(targetPath);
        if (!targetFile.exists()){
            if (targetFile.createNewFile()) {
                System.out.println("创建成功");
            }
        }

        BufferedReader reader = new BufferedReader(new FileReader(resourceFile));
        XSSFWorkbook workbook = new XSSFWorkbook();

        String str =null;
        XSSFSheet createOrder1 = workbook.createSheet("生成单一");
        // 读取第一行
        if ((str = reader.readLine())!=null){
            // 创建行
            XSSFRow row = createOrder1.createRow(0);
            // 逗号分割第一行
            String[] split = str.split(",");
            // 遍历写入
            for (int i = 0; i < split.length; i++) {
                // 创建列(单元格)
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(split[i]);
            }
        }
        var i = 1;
        while ((str = reader.readLine())!=null){
            XSSFRow row = createOrder1.createRow(i);
            String[] split = str.split(",");
            for (int j = 0; j < split.length; j++) {
                // 创建列(单元格)
                XSSFCell cell = row.createCell(i);
                cell.setCellValue(split[j]);
            }
        }
        // 合并单元格
        CellRangeAddress cellAddresses = new CellRangeAddress(1, 3, 0, 1);
        createOrder1.addMergedRegion(cellAddresses);
        // 找到合并的单元格(左上角第一个单元格的位置)设置值
        StylesTable stylesTable = new StylesTable();
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        createOrder1.createRow(1).createCell(0).setCellStyle(cellStyle);
        createOrder1.createRow(1).createCell(0).setCellValue("Hello Workbook");
        workbook.write(new FileOutputStream(targetFile));
        reader.close();
    }
}
